import { Dialog } from 'mand-mobile';
import router from './router';
import store from './store';
import { callNativeApi } from './utils/native';
import { getToken, logout } from './api/login';

const whiteList = ['/login', '/test']; // 不重定向白名单

router.beforeEach((to, from, next) => {
  if (store.getters.isLogin) {
    getToken().then(result => {
      if (result.message === 'success') {
        next();
      } else {
        Dialog.alert({
          content: '登录失效，请重新登录',
          onConfirm: () => {
            logout().then(res => {
              if (res.message === 'success') {
                const loginOut = callNativeApi('dxGoLogin');
                if (!loginOut) {
                  window.location.reload();
                }
              } else {
                Dialog.alert({ content: res.message });
              }
            }).catch(() => {
              Dialog.alert({ content: '失败！' });
            });
          }
        });
      }
    });
  } else if (whiteList.indexOf(to.path) !== -1) {
    next();
  } else {
    if (Object.prototype.hasOwnProperty.call(window, 'dx')) {
      const userInfo = JSON.parse(callNativeApi('dxGetUserinfo'));
      store.dispatch('setUserInfo', userInfo);
    } else if (Object.prototype.hasOwnProperty.call(window, 'dxGetUserinfo')) {
      const userInfo = callNativeApi('dxGetUserinfo');
      store.dispatch('setUserInfo', userInfo);
    }
    const uesrInfo = callNativeApi('dxGetUserinfo');
    if (uesrInfo) {
      if (Object.prototype.hasOwnProperty.call(window, 'dx')) {
        const userInfo = JSON.parse(callNativeApi('dxGetUserinfo'));
        store.dispatch('setUserInfo', userInfo);
      } else if (Object.prototype.hasOwnProperty.call(window, 'dxGetUserinfo')) {
        const userInfo = callNativeApi('dxGetUserinfo');
        store.dispatch('setUserInfo', userInfo);
      }
      next();
    } else {
      next('/login'); // 否则全部重定向到登录页
    }
  }
});

router.afterEach(() => {
});
